package org.oimwrapper.connectors;

import java.io.*;
import java.net.*;
import java.util.jar.*;

/**
 * This contains methods for getting code/jar versions.
 */
public final class OIMCodeVersion {

	/**
	 * Gets a pretty-printed version of a class name for a given class
	 * 
	 * @param Item The class to get the name for.
	 * @return The name of the class.
	 * @exception Exception
	 */
	public final static String getClassName(Class Item) throws Exception {
		String className = "/" + Item.getName().replaceAll("\\.", "/");
		return className;
	}

	/**
	 * Gets the name of the jar file where the class was loaded from.
	 * 
	 * @param Item The class to get the name for.
	 * @return The name of the jar file.
	 * @exception Exception
	 */
	public final static String getJarFile(Class Item) throws Exception {
		String result = "";
		String className = OIMCodeVersion.getClassName(Item);
		URL url = Item.getResource(className + ".class");
		if (url != null) {
			result = url.toString().replaceAll("jar:file:", "").split("!")[0];
		}
		if (File.separator.equals("\\") && result.length() > 0 && result.substring(0, 1).equals("/")) {
			result = result.substring(1);
		}
		return result;
	}
	
	/**
	 * Gets the attribute the jar file based on tags in the manifest.
	 * 
	 * @param JarFile The name of the jar file to get the build date from.
	 * @return The attribute value the jar if present, or an empty string if the value is not found.
	 * @exception Exception
	 */
	private final static String getJarAttribute(String JarFile, String Attribute) throws Exception {
		String result = "";
		JarInputStream jarInputStream = new JarInputStream(new FileInputStream(JarFile));
		if (jarInputStream != null) {
			Manifest manifest = jarInputStream.getManifest();
			if (manifest != null) {
				result = manifest.getMainAttributes().getValue(Attribute);
			}
			jarInputStream.close();
		}
		return result;
	}

	/**
	 * Gets the date on which the jar file was built based on tags in the manifest.
	 * 
	 * @param JarFile The name of the jar file to get the build date from.
	 * @return The build date of the jar if present, or an empty string if the value is not found.
	 * @exception Exception
	 */
	public final static String getJarBuildDate(String JarFile) throws Exception {
		return getJarAttribute(JarFile, "Build-Date");
	}
	
	/**
	 * Gets the SVN revision on which the jar file was built based on tags in the manifest.
	 * 
	 * @param JarFile The name of the jar file to get the build date from.
	 * @return The svn revision of the jar if present, or an empty string if the value is not found.
	 * @exception Exception
	 */
	public final static String getJarSvnRevision(String JarFile) throws Exception {
		return getJarAttribute(JarFile, "SVN-Revision");
	}
}